#!/usr/bin/python
# coding=utf-8

import os
import sys
import shutil

RELEASE_DIR = 'release'

manifest = '../comwan~1.apk.decode/AndroidManifest.xml'
manifest_bk = '../comwan~1.apk.decode/AndroidManifest.xml.bk'

apk_file = 'release/bin/tmp.apk'

argv_len = 0

#--通过命令输入的渠道文件名 取得渠道名称
channels = [i.strip() for i in open(sys.argv[-1]).read().split() if i.strip()]
# channels = ['goapk']

def backup():
#    os.system('cp %s %s' % (manifest, manifest_bk))
    shutil.copyfile(manifest, manifest_bk)

def restore():
#    os.system('rm %s' % manifest)
#    os.system('mv %s %s' % (manifest_bk, manifest))
    os.remove(manifest)
    os.rename(manifest_bk, manifest)

def replace_channel(channel_name):
    #--可以看出来python的语法很nb啊，这么两句就完成了manifest的xml解析
    from xml.dom.minidom import parse
    dom = parse(open(manifest))
    #--替换我们想要替换的内容，这里我们替换我们的渠道信息
    for i in dom.getElementsByTagName('meta-data'):
        if i.getAttribute('android:name') == 'NIGG_CHANNEL_ID':
            i.setAttribute('android:value', channel_name)

    open(manifest, 'w').write(dom.toxml().encode('utf-8'))

def rename_apk(channel_name):
#    apk_file = 'bin/SexGirl-release.apk'
    channel_apk_file = '%s/xxxx-release-%s.apk' % (RELEASE_DIR, channel_name)
    #--渠道内容变了，apk包名也需要更改与之对应起来
#    os.system('mv %s %s' % (apk_file, channel_apk_file))
    os.rename(apk_file, channel_apk_file)
    

def empty_dir(dir):
    for root, dirs, files in os.walk(dir):
        for f in files:
            os.unlink(os.path.join(root, f))
        for d in dirs:
            shutil.rmtree(os.path.join(root, d))

def main():
    #--创建apk的release目录
    if not os.path.exists(RELEASE_DIR):
        os.mkdir(RELEASE_DIR)

    backup()
#    os.system('rm %s/*' % RELEASE_DIR)
    empty_dir(RELEASE_DIR)
    
    
    #重点的编译的地方，循环编译apk。实际上，eclipse等IDE环境的编译在背后也是做的类似这样的操作。当然这里使用了ant来编译，所以执行本脚本的前提是安装了ant
    for i in channels:
#        os.system('ant clean')
        replace_channel(i)
#        os.system('ant release')
        os.system('java -jar apktool.jar b -f -d ../comwan~1.apk.decode %s' % apk_file)
        rename_apk(i)

    restore()


if __name__ == '__main__':
    argv_len = len(sys.argv)
    if argv_len >= 2 and sys.argv[1] == '-h':
        print ("Usage:bat_pack.py channels.txt ")
        exit(1)
    if not sys.argv[-1].endswith('txt'):
        print 'bat_pack.py channels.txt'
        exit(1)

    main()
